package com.xy.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ConsumerController {
    /**
     * 在未使用负载均衡配置前，需要指定请求的服务提供者地址
     */
//    private static final String REST_URL_PREFIX = "http://localhost:8001";
    /**
     * 使用负载均衡后，此处需要替换成对应的服务名称，注意全要大写
     */
    private static final String REST_URL_PREFIX = "http://API-PROVIDER";
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/dept/get/{id}")
    public String getDept(@PathVariable(value = "id") Integer id) {
        String res = restTemplate.getForObject(REST_URL_PREFIX + "/provider/dept/get/" + id, String.class);
        if (res == null || res.length() <= 0) {
            // 模拟抛出异常的情况
            throw new RuntimeException("该ID： " + id + " 不存在");
        }
        return res;
    }

    @RequestMapping("/consumer/dept/list")
    public List listDept() {
        return restTemplate.getForObject(REST_URL_PREFIX + "/provider/dept/list", List.class);
    }
}
